#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#include "cJSON.h"
int regist(long phonenum, struct sockaddr_in *seraddr); 
// 定义regist函数，用于注册逻辑，返回注册成功获取的ID，参数为电话号码和服务器地址结构体指针
int regist(long phonenum, struct sockaddr_in *seraddr) 
{
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        perror("socket");
        exit(-1);
    }

    cJSON *json = NULL;
    char type[20] = "register";
    json = cJSON_CreateObject();
    cJSON_AddItemToObject(json, "type", cJSON_CreateString(type));
    cJSON_AddItemToObject(json, "phonenum", cJSON_CreateNumber(phonenum));
    char *dest = NULL;
    dest = cJSON_Print(json);
    char buf[100] = {0};
    memcpy(buf, dest, strlen(dest));
    int ret = sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)seraddr, sizeof(struct sockaddr));
    if (ret == -1) {
        printf("sendto register");
        exit(-1);
    }

    // 接收结果
    char result[100] = {0};
    memset(&result, 0, sizeof(result));
    struct sockaddr_in cliaddr;
    memset(&cliaddr, 0, sizeof(cliaddr));
    int len = sizeof(struct sockaddr);
    ret = recvfrom(sock, result, sizeof(result), 0, (struct sockaddr *)&cliaddr, &len);
    if (ret == -1) {
        printf("recvfrom ID");
        exit(-1);
    }

    cJSON *node = NULL;
    json = cJSON_Parse(result);
    node = cJSON_GetObjectItem(json, "ID");
    if (node == NULL) {
        printf("can't find ID\n");
        return -1;
    }
    else if (node->type == cJSON_Number) {
        int ID = node->valueInt;
        close(sock);
        return ID;
    }
    close(sock);
    return -1;
}

int main(int argc, const char* argv[]) {
    // 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    int ret = 0;
    if (sock == -1) {
        perror("socket");
        exit(-1);
    }

    // 定义地址
    struct sockaddr_in seraddr;
    memset(&seraddr, 0, sizeof(struct sockaddr_in));
    seraddr.sin_family = AF_INET;
    seraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    // htons：转化为可以java理解的
    seraddr.sin_port = htons(6868);

    // 注册
    printf("是否注册？\n");
    printf("1---注册\n");
    printf("2---登录\n");
    printf("3---退出\n");
    printf("输入数字进行你的选择\n");
    int val = 0;
    scanf("%d", &val);
    long phonenum = 0;
    switch (val) {
    case 1:
        printf("请输入你的注册号码\n");
        scanf("%ld", &phonenum);
        int ID = regist(phonenum, &seraddr);
        // 注册失败处理
        while (ID == -1) 
		{
            printf("请输入新的号码");
            scanf("%ld", &phonenum);
            ID = regist(phonenum, &seraddr);
        }
        // 注册成功
        printf("%ld用户已注册成功,您的登录密码为您的手机号\n", ID);
        break;
    case 2:
        break;
    case 3:
        break;
    default:
        break;
    }
    return 0;
}